#include "widget.h"
#include "ui_widget.h"
#include "messageboxutil.h"
#include <QTimer>
#include <QMessageBox>
#include <QThread>
#include <QSignalTransition>
#include <QSettings>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonDocument>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);


    QTimer::singleShot(0, this, &Widget::showLoginDialog);
    do_initSerialPort();
    InitEntIPPort();
    initGroupData();

    // 连接plc状态信号
    connect(&plc_port, &ModbusSerialTest::newStatusBit, this, &Widget::do_updatelatestStatusCode);


//    connect(&plc_port, &ModbusSerialTest::shiftOnAStatus, this, &Widget::do_updateShiftOnAStatusStatusCode);

    connect(&plc_port, &ModbusSerialTest::TopSidelightControlsData, this, &Widget::sendTopRoSideLightAdjustData);
    connect(&plc_port, &ModbusSerialTest::BottomlightControlsData, this, &Widget::sendBottomLightAdjustData);

    connect(&plc_port, &ModbusSerialTest::sendDevCurrentGroup, this, &Widget::do_compareWorkGroup);

    connect(&plc_port, &ModbusSerialTest::topPhotoRequest, [=](uint16_t state){
        m_topPhotoRequest = state;
    });

    connect(&plc_port, &ModbusSerialTest::ABCD_PhotoRequest, [=](uint16_t state){
        m_ABCD_PhotoRequest = state;
    });

    connect(&plc_port, &ModbusSerialTest::bottomPhotoRequest, [=](uint16_t state){
        m_bottomPhotoRequest = state;
    });


    connect(&plc_port, &ModbusSerialTest::sensorStateMap, [=](QMap<QString, uint8_t> map){

        QString feedSensorStatusText = map.value("输入口检测信号") ? "检测到" : "未检测到";
        QString liftSensorStatusText = map.value("顶升气缸正限位") ? "检测到" : "未检测到";
        QString chainWidthText = map.value("调宽气缸负限位") ? "窄" : "宽";
        QString rotateSensorStatusText = map.value("旋转轴原点") ? "检测到" : "未检测到";
        QString cuttingSensorStatusText = map.value("输出口检测信号") ? "检测到" : "未检测到";

        ui->LineEdit_feedSensorStatus->setText(feedSensorStatusText);
        ui->LineEdit_liftSensorStatus->setText(liftSensorStatusText);
        ui->lineEdit_chainWidth->setText(chainWidthText);
        ui->LineEdit_rotateSensorStatus->setText(rotateSensorStatusText);
        ui->LineEdit_cuttingSensorStatus->setText(cuttingSensorStatusText);

        emit plcChainWidthCurrentSize(chainWidthText);
    });

     connect(this, &Widget::pauseState, [=](){
        
     });


    // 连接clicked信号到槽函数
    connect(ui->btn_switch, &QPushButton::clicked, [=](){

        QString styleSheet;
        if (!device_switch_flag) {
            //切换为蓝色
            styleSheet = "QPushButton{ color:white; background-color:rgb(0,153,255);border:3px solide rgb(0,153,255);border-radius:6px;font:16pt;} "
                         "QPushButton:hover{background-color:rgb(0,120,200);}"
                         "QPushButton:pressed{color:white;background-color:rgb(75,75,75);border:2px solid rgb(0,153,255);border-radius:6px;}";
            ui->btn_switch->setText("在线启动");

        } else {
            //切换为红色
            styleSheet = "QPushButton{ color:white; background-color:rgb(255,127,127);border:3px solide rgb(225,127,127);border-radius:6px;font:16pt;} "
                         "QPushButton:hover{background-color:rgb(200,100,100);}"
                         "QPushButton:pressed{color:white;background-color:rgb(75,75,75);border:2px solid rgb(225,127,127);border-radius:6px;}";
            ui->btn_switch->setText("紧急暂停");
        }
        ui->btn_switch->setStyleSheet(styleSheet);
    });


    // 调用函数并获取状态步骤
    currentSteps = readStepsFromFile("steps.txt");


    MyStateMachineInit();


    // 默认自动模式
    ui->btn_Stop->setEnabled(false);
    ui->btn_operPause->setEnabled(false);
    ui->btn_shiftOnA->setEnabled(false);
    ui->on_resetGlobal->setEnabled(false);
    ui->btn_LightSourceControl->setEnabled(false);
    ui->btn_camAdjust->setEnabled(false);
}

Widget::~Widget()
{
    deleteStateMachine();// 释放状态机资源

    delete ui;
}

void Widget::showLoginDialog() {
    // 创建登录对话框
    Dialog_login login(this);
    // 显示登录对话框
    if(login.exec()==QDialog::Rejected)
    {
        this->close();
    }
}

// 获取步骤文件
QStringList Widget::readStepsFromFile(const QString &fileName) {
    QStringList steps;
    QFile file(fileName);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件";
        return steps;
    }

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        steps.append(line);
    }

    file.close();
    return steps;
}

void Widget::InitEntIPPort()
{
    QSettings settings("config/systemConfig.ini", QSettings::IniFormat);

    settings.beginGroup("system");

    QString netIP = settings.value("netIP").toString();

    QString netPort = settings.value("netPort").toString();

    settings.endGroup();

    // 初始化IP端口
    m_http = new HttpRequest(this, netIP + ":" + netPort);
}

void Widget::do_setCurrentGroupSize(QString groupSize)
{
    ui->LineEdit_workGroupSize->setText(groupSize);
}

void Widget::do_setCurrentGroupName(QString groupName)
{
    ui->LineEdit_currentWorkGroup->setText(groupName);
}
//void timerReadTimeout()
//{
//    // 读工作组,0.5 read 2times
//      timerReadPf.stop();
//    plc_port.sendModbusRequest(3, 0xA466, (currGroupNum) * 400);


//}
void Widget::do_compareWorkGroup(uint8_t x)
{
//    QString currentGroupStr = ui->LineEdit_currentWorkGroup->text().trimmed();

//    if(currentGroupStr.isEmpty())
//    {
//        if (QMessageBox::Yes != QMessageBox::question(this, "报错", QString("当前没有选择工作组"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No)) {

//        }
//        return;
//    }



//    QStringList currentGroupNumList = currentGroupStr.split("group");

//    if(x == currGroupNum)
//    {
//        plc_port.setSendModbusRequest(5, 1102, 0xFF00);
//        plc_port.setSendModbusRequest(5, 1102, 0x00);

//        emit resetIdleState();
//    }
//    else{
//        ;
//    }
}
// 用户组同步更新到plc
void Widget::updatePlcGroupData(const QString &groupName)
{
    qDebug() << "plc更新配方: " << groupName;
    QStringList strlist = groupName.split("group");
    if(strlist.size() >= 2 )
    {
        if(strlist.at(1).toInt() >= 0)
        {
            int16_t currGroupNum = strlist.at(1).toInt();
            // 选择工作组,0.5 read 2times
            plc_port.sendModbusRequest(6, 0xA466, (currGroupNum) * 400);
//            timerReadPf.start(200);
//            plc_port.sendModbusRequest(3, 0xA466, 1);
//            // 复位
//            plc_port.setSendModbusRequest(5, 1102, 0xFF00);
//            plc_port.setSendModbusRequest(5, 1102, 0x00);

            emit resetIdleState();
        }
    } else {
        qDebug() << strlist << "当前配置组名有问题...";
    }
}

// 控制面板
void Widget::on_btn_selectWorkGroup_clicked()
{

    Dialog_selectWorkGroup *dialog = new Dialog_selectWorkGroup(this);
    connect(dialog, &Dialog_selectWorkGroup::currentGroupName, this, &Widget::do_setCurrentGroupName);
    connect(dialog, &Dialog_selectWorkGroup::currentGroupSize, this, &Widget::do_setCurrentGroupSize);
    connect(this, &Widget::plcChainWidthCurrentSize, dialog, &Dialog_selectWorkGroup::do_setCurrentGroupSize);
    if(dialog->exec() == QDialog::Accepted) {
        QString groupBlo = map_currentGroup.value("currentGroup");
        GetCurrentGroupData();
        if(groupBlo != map_currentGroup.value("currentGroup"))
        {
            updatePlcGroupData(map_currentGroup.value("currentGroup"));// 用户组同步更新到plc
        }
    }
    disconnect(this, &Widget::plcChainWidthCurrentSize, dialog, &Dialog_selectWorkGroup::do_setCurrentGroupSize);
    disconnect(dialog, &Dialog_selectWorkGroup::currentGroupName, this, &Widget::do_setCurrentGroupName);
    disconnect(dialog, &Dialog_selectWorkGroup::currentGroupSize, this, &Widget::do_setCurrentGroupSize);


    if(dialog != nullptr)
    {
        delete dialog;
    }
}

void Widget::GetCurrentGroupData()
{
    // 创建 QSettings 对象并加载 INI 文件
    QSettings *settings = new QSettings("config/workGroupConfig.ini", QSettings::IniFormat);

    // 获取所有的组
    QStringList groups = settings->childGroups();
    QString currentGroup = "current";

    if (groups.isEmpty()) {
        qDebug() << "No groups found in the INI file.";
    } else {
        // 初始化当前组索
        int currentGroupIndex = 0;
        // 显示当前组信息
        if(currentGroup.isEmpty())
        {
            currentGroup = groups[currentGroupIndex];
        }
        settings->beginGroup(currentGroup);
        currentGroup = settings->value("group").toString();
        settings->endGroup();
        qDebug() << "Current group:" << currentGroup;

        // 显示当前组的所有键值对
        settings->beginGroup(currentGroup);

        QMap<QString, QString> map_group;

        map_group.insert("currentGroup", settings->value("name").toString());
        map_group.insert("size", settings->value("size").toString());
        map_group.insert("topCameraLightValue", QString::number(settings->value("top_cam_lightValue_1").toInt()));
        map_group.insert("sideCameraLightValue", QString::number(settings->value("side_cam_lightValue_1").toInt()));
        map_group.insert("sideCameraBottomLightValue", QString::number(settings->value("side_cam_fillLight").toInt()));
        map_group.insert("bottomCameraLightValue", QString::number(settings->value("bottom_cam_lightValue_2").toInt()));
        map_group.insert("topCameraFoucs", QString::number(settings->value("top_cam_focusRing_value_1").toInt()));
        map_group.insert("sideCameraFoucs", QString::number(settings->value("side_cam_focusRing_value_2").toInt()));
        settings->endGroup();

        map_currentGroup = map_group;
    }
    delete settings;
}

void Widget::do_checkPortConnection()
{

}


void Widget::initGroupData()
{
    GetCurrentGroupData();

//    QSettings settings("config/systemConfig.ini", QSettings::IniFormat);
//    settings.beginGroup("system");
//    ui->LineEdit_configFileName->setText(settings.value("configFilePath").toString());
//    settings.endGroup();

//    updatePlcGroupData(map_currentGroup.value("currentGroup"));// 用户组同步更新到plc

//    ui->LineEdit_currentWorkGroup->setText(map_currentGroup.value("currentGroup"));
//    ui->LineEdit_workGroupSize->setText(map_currentGroup.value("size"));
}


void Widget::on_btn_configWorkGroup_clicked()
{

    Dialog_configWorkGroupParas *dialog = new Dialog_configWorkGroupParas(this);
    dialog->exec();

    if(dialog != nullptr)
    {
        delete dialog;
    }
}


void Widget::on_btn_systemConfig_clicked()
{
    Dialog_configSystermParas *dialog = new Dialog_configSystermParas(this);
    dialog->exec();

    if(dialog != nullptr)
    {
        delete dialog;
    }
}


void Widget::on_btn_switchHandOper_clicked()
{
    if(m_switchHandOperFlag)
    {
        ui->btn_switchHandOper->setText("切换手动操作");

        m_switchHandOperFlag = false;

        ui->btn_Stop->setEnabled(false);
        ui->btn_operPause->setEnabled(false);
        ui->btn_shiftOnA->setEnabled(false);
        ui->on_resetGlobal->setEnabled(false);
        ui->btn_LightSourceControl->setEnabled(false);
        ui->btn_camAdjust->setEnabled(false);
    } else {
        ui->btn_switchHandOper->setText("切换自动操作");
        m_switchHandOperFlag = true;

        ui->btn_Stop->setEnabled(true);
        ui->btn_operPause->setEnabled(true);
        ui->btn_shiftOnA->setEnabled(true);
        ui->on_resetGlobal->setEnabled(true);
        ui->btn_LightSourceControl->setEnabled(true);
        ui->btn_camAdjust->setEnabled(true);
    }
}



void Widget::do_checkCode(QString code)
{
    qDebug() << "产品码：" << code;

    plc_port.plcSendPulse(5, 1100);// 发送启动脉冲信号

}

// 停止设备
void Widget::on_btn_Stop_clicked()
{
    plc_port.plcSendPulse(5, 1107);// 发送停止脉冲信号

    emit resetForScanState();// 发送复位信号, 切换到等待扫码状态
}

// 暂停
void Widget::on_btn_operPause_clicked()
{
    plc_port.plcSendPulse(5, 1101);// 发送暂停脉冲信号

    emit pauseState();
}

// 全局复位
void Widget::on_on_resetGlobal_clicked()
{
    // 创建一个确认对话框
    QMessageBox *msgBox = new QMessageBox();
    msgBox->setText("确认要复位吗？");
    msgBox->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox->setDefaultButton(QMessageBox::No); // 默认按钮设置为“否”

    // 执行对话框并获取结果
    // 根据结果执行操作，如果是“是”，则全局复位了
    if (QMessageBox::Yes == msgBox->exec()) {
        qDebug() << "全局复位";

        plc_port.plcSendPulse(5, 1102);// 发送复位脉冲信号

        emit resetIdleState();

        delete msgBox;
    }
}

//光源控制
void Widget::on_btn_LightSourceControl_clicked()
{
    Dialog_LightControl *dialog = new Dialog_LightControl(this);

    connect(dialog,SIGNAL(sendTopRoSideLightAdjustData(QString)),this,SLOT(sendTopRoSideLightAdjustData(QString)));
    connect(dialog,SIGNAL(sendBottomLightAdjustData(QString)),this,SLOT(sendBottomLightAdjustData(QString)));
    connect(&top_side_light_sport,SIGNAL(newDataReceived(QString)),dialog,SLOT(getRecv(QString)));
    connect(&bottom_light_sport,SIGNAL(newDataReceived(QString)),dialog,SLOT(getRecv(QString)));
    sendTopRoSideLightAdjustData("SA#");
    sendTopRoSideLightAdjustData("SB#");
    dialog->exec();
    disconnect(dialog,SIGNAL(sendTopRoSideLightAdjustData(QString)),this,SLOT(sendTopRoSideLightAdjustData(QString)));
    disconnect(dialog,SIGNAL(sendBottomLightAdjustData(QString)),this,SLOT(sendBottomLightAdjustData(QString)));
    disconnect(&top_side_light_sport,SIGNAL(newDataReceived(QString)),dialog,SLOT(getRecv(QString)));
    disconnect(&bottom_light_sport,SIGNAL(newDataReceived(QString)),dialog,SLOT(getRecv(QString)));

    if(dialog != nullptr)
    {
        delete dialog;
    }
}

void Widget::sendTopRoSideLightAdjustData(QString dat)
{
//    qDebug()<<dat;
    top_side_light_sport.sendData(dat);
}

void Widget::sendBottomLightAdjustData(QString dat)
{
//    qDebug()<<dat;
    bottom_light_sport.sendData(dat);
}

QByteArray Widget::intToByteArray(int value)
{
    QByteArray byteArray;
    byteArray.resize(4);

    byteArray[0] = (uint8_t)(value >> 24) & 0xFF;
    byteArray[1] = (uint8_t)(value >> 16) & 0xFF;
    byteArray[2] = (uint8_t)(value >> 8) & 0xFF;
    byteArray[3] = (uint8_t) value & 0xFF;

    return byteArray;
}

QByteArray Widget::formSetAngleData(int16_t angle)
{
    QByteArray dat;
    dat.append(0x01);
    dat.append(0x64);
    dat.append(0x01);
    int temp = 100 * 16384 /6000;
    dat+=intToByteArray(temp);
    temp = angle * 16384 /360;
    dat+=intToByteArray(temp);

    dat.append('\x00');
    dat.append('\x00');
    dat.append('\x00');

    return dat;
}


void Widget::sendSideFormSetData(int16_t angle)
{
    QByteArray dat = formSetAngleData(angle);
    getSideAdjustData(dat);

    qDebug() << "侧边镜头调焦：" << angle;
}

void Widget::sendTopFormSetData(int16_t angle)
{
    QByteArray dat = formSetAngleData(angle);
    getTopAdjustData(dat);

    qDebug() << "顶部镜头调焦：" << angle;
}

//镜头调节
void Widget::on_btn_camAdjust_clicked()
{
    Dialog_camAdjust *dialog = new Dialog_camAdjust(this);
    connect(dialog,&Dialog_camAdjust::sendTopAdjustData,this, &Widget::getTopAdjustData);
    connect(dialog,&Dialog_camAdjust::sendSideAdjustData,this, &Widget::getSideAdjustData);
    connect(&top_cam_focus_sport, static_cast<void (SerialPortHandler::*)(const QByteArray)>(&SerialPortHandler::newDataReceived), dialog, &Dialog_camAdjust::getTopRecv);
    connect(&side_cam_focus_sport, static_cast<void (SerialPortHandler::*)(const QByteArray)>(&SerialPortHandler::newDataReceived), dialog, &Dialog_camAdjust::getSideRecv);

    dialog->exec();

    disconnect(dialog,&Dialog_camAdjust::sendTopAdjustData,this, &Widget::getTopAdjustData);
    disconnect(dialog,&Dialog_camAdjust::sendSideAdjustData,this, &Widget::getSideAdjustData);
    disconnect(&top_cam_focus_sport, static_cast<void (SerialPortHandler::*)(const QByteArray)>(&SerialPortHandler::newDataReceived), dialog, &Dialog_camAdjust::getTopRecv);
    disconnect(&side_cam_focus_sport, static_cast<void (SerialPortHandler::*)(const QByteArray)>(&SerialPortHandler::newDataReceived), dialog, &Dialog_camAdjust::getSideRecv);

    if(dialog != nullptr)
    {
        delete dialog;
    }
}
void Widget::getTopAdjustData(QByteArray dat)
{

    QString str_dat = "Top 发送给镜头(HEX)：";

    uint16_t wcrc = ModbusCRC16(dat);
//    qDebug()<<"CRC码：低字节:"<< QString("%1").arg(uint8_t(wcrc), 2, 16, QChar('0')).toUpper()
//            <<" 高字节:"<< QString("%1").arg(uint8_t(wcrc>>8), 2, 16, QChar('0')).toUpper();

    dat.append(uint8_t(wcrc));
    dat.append(uint8_t(wcrc>>8));

    qDebug() << str_dat << dat.toHex().toUpper();

    top_cam_focus_sport.sendData(dat);
}

void Widget::getSideAdjustData(QByteArray dat)
{

    QString str_dat = "Side 发送给镜头(HEX)：";

    uint16_t wcrc = ModbusCRC16(dat);
//    qDebug()<<"CRC码：低字节:"<< QString("%1").arg(uint8_t(wcrc), 2, 16, QChar('0')).toUpper()
//            <<" 高字节:"<< QString("%1").arg(uint8_t(wcrc>>8), 2, 16, QChar('0')).toUpper();

    dat.append(uint8_t(wcrc));
    dat.append(uint8_t(wcrc>>8));

    qDebug() << str_dat << dat.toHex().toUpper();

    side_cam_focus_sport.sendData(dat);
}

void Widget::do_updateShiftOnAStatusStatusCode(uint8_t state)
{
    if(state)
    {
        ui->LineEdit_liftSensorStatus->setText("顶升到位");
    } else {
        ui->LineEdit_liftSensorStatus->setText("顶升未到位");
    }
}

void Widget::do_updatelatestStatusCode(const uint16_t statusCode)
{
    qDebug() << "接收到新状态 ：" << statusCode;

    plcStateBit = statusCode;

    if(statusCode >= currentSteps.size())
    {
        ui->LineEdit_currentStep->setText("暂时没有该状态位");
        return;
    }

    // 更新到显示框
    ui->LineEdit_latestStatusCode->setText(QString::number(statusCode));
    ui->LineEdit_currentStep->setText(currentSteps.at(statusCode));
}


void Widget::do_initSerialPort()
{


    bool FlagLight = top_side_light_sport.openPort(2,"topCameraLightNuberOf1");
    if(!FlagLight)
    {
        top_side_light_sport.setConnectStatus(false);
//        ui->LineEdit_lightConnStateA->setText("未连接");
//        ui->LineEdit_lightConnStateA_2->setText("未连接");
        setTextColor(ui->LineEdit_lightConnStateA, "未连接", Qt::black);
        setTextColor(ui->LineEdit_lightConnStateA_2, "未连接", Qt::black);
        QMessageBox::warning(this,"提示","工位1顶部光源端口 打开失败!");
    } else {
        top_side_light_sport.setConnectStatus(true);
//        ui->LineEdit_lightConnStateA->setText("已连接");
//        ui->LineEdit_lightConnStateA_2->setText("已连接");
        setTextColor(ui->LineEdit_lightConnStateA, "已连接", Qt::green);
        setTextColor(ui->LineEdit_lightConnStateA_2, "已连接", Qt::green);
    }

    bool topFlagFocusRing = top_cam_focus_sport.openPort(1,"topCameraFocusRingNuberOf1");
    if(!topFlagFocusRing)
    {
        top_cam_focus_sport.setConnectStatus(false);
//        ui->LineEdit_cameraConnStateA->setText("未连接");
        setTextColor(ui->LineEdit_cameraConnStateA, "未连接", Qt::black);
        QMessageBox::warning(this,"提示","工位1顶部镜头调焦端口 打开失败!");
    } else {
        top_cam_focus_sport.setConnectStatus(true);
//        ui->LineEdit_cameraConnStateA->setText("已连接");
        setTextColor(ui->LineEdit_cameraConnStateA, "已连接", Qt::green);
    }

    bool bottomFlagLight = bottom_light_sport.openPort(2,"bottomCameraLightNuberOf2");
    if(!bottomFlagLight)
    {
        bottom_light_sport.setConnectStatus(false);
//        ui->LineEdit_otherInfo_2->setText("未连接");
        setTextColor(ui->LineEdit_otherInfo_2, "未连接", Qt::black);
        QMessageBox::warning(this,"提示","工位2底部光源端口 打开失败!");
    } else {
        bottom_light_sport.setConnectStatus(true);
//        ui->LineEdit_otherInfo_2->setText("已连接");
        setTextColor(ui->LineEdit_otherInfo_2, "已连接", Qt::green);
    }

    bool sideFlagFocusRing = side_cam_focus_sport.openPort(1,"LineEdit_sideCameraFocusRingNuberOf1");
    if(!sideFlagFocusRing)
    {
        bottom_light_sport.setConnectStatus(false);
//        ui->LineEdit_cameraConnStateB->setText("未连接");
        setTextColor(ui->LineEdit_cameraConnStateB, "未连接", Qt::black);
        QMessageBox::warning(this,"提示","工位1侧面镜头调焦端口 打开失败!");
    } else {
        bottom_light_sport.setConnectStatus(true);
//        ui->LineEdit_cameraConnStateB->setText("已连接");
        setTextColor(ui->LineEdit_cameraConnStateB, "已连接", Qt::green);
    }

    if(plc_port.startPort())
    {
      plc_port.setPlcConnectState(true);
//      ui->LineEdit_PlcState->setText("已连接");
      setTextColor(ui->LineEdit_PlcState, "已连接", Qt::black);
      plc_state_flag = true;
    } else {
        plc_port.setPlcConnectState(false);
        QMessageBox::warning(this,"提示","PLC断开打开失败!");
        setTextColor(ui->LineEdit_PlcState, "PLC断开打开失败!", Qt::green);
    }

    if(FlagLight && topFlagFocusRing && bottomFlagLight && sideFlagFocusRing && plc_state_flag)
    {
        m_portGlobalFlag = true;
    } else {
        m_portGlobalFlag = false;
    }


//      m_portConnection->start(5000); // 设置检测时间，每五秒钟检测一次
    m_checkPortFlag = true;
    m_checkPortTime = 3;// 设置检测时间，每3秒钟检测一次

}

void Widget::do_closeSerialPort()
{
    top_side_light_sport.closePort();
    top_cam_focus_sport.closePort();
    bottom_light_sport.closePort();
    side_cam_focus_sport.closePort();


    ui->LineEdit_lightConnStateA->setText("已断开");
    ui->LineEdit_lightConnStateA_2->setText("已断开");

    ui->LineEdit_cameraConnStateA->setText("已断开");

    ui->LineEdit_otherInfo_2->setText("已断开");

    ui->LineEdit_cameraConnStateB->setText("已断开");


    if(true == plc_state_flag)
    {
        plc_port.closePort();
        ui->LineEdit_PlcState->setText("已断开");
        plc_state_flag =  false;
    }
}


void Widget::on_btn_switch_clicked()
{
    if(ui->LineEdit_currentWorkGroup->text().isEmpty())
    {
        qDebug() << "当前组名不能为空...";
        return;
    }

    if(ui->LineEdit_workGroupSize->text().isEmpty())
    {
        qDebug() << "当前尺寸大小不能为空...";
        return;
    }

    if(false == device_switch_flag)
    {
        QString str = ui->LineEdit_workGroupSize->text();

        if(str.isEmpty()){
            return;
        }

        QStringList str_list = str.split("*");

        if(str_list.size() != 3){
            return;
        }

        uint16_t chain_L = str_list.at(0).toInt();
        uint16_t chain_W = str_list.at(1).toInt();

        if(chain_L == 450 && chain_W == 450)
        {
            if (QMessageBox::Yes != QMessageBox::question(this,
                                                          "请核对设备信息",
                                                          QString("请确认以下信息：\n\t1.当前产品的尺寸为: %1\n"
                                                                  "\t2.设备倍速链为【%2限位】\n"
                                                                  "请认真检查产品尺寸信息和配方，避免误操作！").arg(str).arg(ui->lineEdit_chainWidth->text()),
                                                          QMessageBox::Yes | QMessageBox::No,
                                                          QMessageBox::No)) {
                return;
            }
        }

        device_switch_flag = true;
        {
            ui->btn_Stop->setEnabled(false);
            ui->btn_operPause->setEnabled(false);
            ui->btn_shiftOnA->setEnabled(false);
            ui->on_resetGlobal->setEnabled(false);
            ui->btn_LightSourceControl->setEnabled(false);
            ui->btn_camAdjust->setEnabled(false);

        }

        ui->btn_codeScanStart->setEnabled(false);
        ui->btn_selectWorkGroup->setEnabled(false);
        ui->btn_configWorkGroup->setEnabled(false);
        ui->btn_switchHandOper->setEnabled(false);
        ui->btn_systemConfig->setEnabled(false);


//        // 设置定时器间隔为1000毫秒（即1秒）
//        StateMachineTimer->start(1000);
        m_nextStateFlag = true;// 状态机跳转开启
    } else {
        device_switch_flag = false;

        if(m_switchHandOperFlag)
        {
            ui->btn_Stop->setEnabled(true);
            ui->btn_operPause->setEnabled(true);
            ui->btn_shiftOnA->setEnabled(true);
            ui->on_resetGlobal->setEnabled(true);
            ui->btn_LightSourceControl->setEnabled(true);
            ui->btn_camAdjust->setEnabled(true);


        }
        ui->btn_codeScanStart->setEnabled(true);
        ui->btn_selectWorkGroup->setEnabled(true);
        ui->btn_configWorkGroup->setEnabled(true);
        ui->btn_switchHandOper->setEnabled(true);
        ui->btn_systemConfig->setEnabled(true);


        on_btn_Stop_clicked();// plc设备停止，状态回到等待扫描
//        StateMachineTimer->stop();// 状态机定时器停止
        m_nextStateFlag = false;// 状态机跳转停止

    }

//    ui->btn_switch->setEnabled(false);
}

//CRC16计算函数
uint16_t Widget::ModbusCRC16(QByteArray senddata)
{
    int len=senddata.size();
    uint16_t wcrc=0XFFFF;//预置16位crc寄存器，初值全部为1
    uint8_t temp;//定义中间变量
    int i=0,j=0;//定义计数
    for(i=0;i<len;i++)//循环计算每个数据
    {
       temp=senddata.at(i);
       wcrc^=temp;
       for(j=0;j<8;j++){
          //判断右移出的是不是1，如果是1则与多项式进行异或。
          if(wcrc&0X0001){
              wcrc>>=1;//先将数据右移一位
              wcrc^=0XA001;//与上面的多项式进行异或
          }
          else//如果不是1，则直接移出
              wcrc>>=1;//直接移出
       }
    }
    temp=wcrc;//crc的值
    return wcrc;
}


void Widget::on_btn_shiftOnA_clicked()
{
    static bool shiftOnA_flag = false;

    if(false == shiftOnA_flag)
    {
        shiftOnA_flag = true;
        ui->btn_shiftOnA->setText("A位下降");
        plc_port.setSendModbusRequest(0x05, 0x020C, 0xFF00);
    }else{
        shiftOnA_flag = false;
        ui->btn_shiftOnA->setText("A位顶升");
        plc_port.setSendModbusRequest(0x05, 0x020C, 0x00);
    }

}

//void Widget::on_btn_sideModule_clicked()
//{
//    Dialog_ModuleControl dialog(this, "侧边模组位置");
//    dialog.exec();
//}

//void Widget::on_btn_topModule_clicked()
//{
//    Dialog_ModuleControl dialog(this, "顶部模组位置");
//    dialog.exec();
//}

void Widget::do_setCurrentGroupData(const QMap<QString, QString> map_group)
{
    map_currentGroup = map_group;

    ui->LineEdit_currentWorkGroup->setText(map_currentGroup.value("currentGroup"));
    ui->LineEdit_workGroupSize->setText(map_currentGroup.value("size"));

    emit sendCurrentWorkGroupData(map_currentGroup);

    qDebug() << "收到了 Map_Group:" << map_group;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* MyStateMachine Code */
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void Widget::MyStateMachineInit()
{
    InitMachine();

    // 初始化定时器
    StateMachineTimer = new QTimer(this);
    // 连接定时器的timeout()信号到自定义槽函数
    connect(StateMachineTimer, &QTimer::timeout, this, &Widget::onTimeoutStateMachine);
    // 设置定时器间隔为1000毫秒（即1秒）
    StateMachineTimer->start(1000);

    // 启动状态机
    machine->start();
}

void Widget::InitMachine()
{
    // 创建状态机
    machine = new QStateMachine(this);

    machine->addTransition(this, &Widget::toNextState, stoppedState);

    // 创建状态
    idleState = new QState(machine);// 设备状态自检，跳转到等待扫描状态

//        stateInit = new QState(machine); // 设备初始化

    forScanState = new QState(machine);// 扫描成功或点击启动按键，倍速链启动，写缓冲区，到达工位一后，跳转拍摄状态

    cameraState = new QState(machine); // 拍摄状态，依次进行顶端、A面、B面、C面、D面、底部拍摄，所有拍摄完毕后，跳转

    resetStartedState = new QState(machine);// 产品下料，下料完毕，模组复位后，跳转等待扫描

    stoppedState = new QState(machine); // 暂停状态

    machine->setInitialState(idleState);// 设置初始状态


    idleState->addTransition(this, &Widget::resetIdleState, idleState);
    forScanState->addTransition(this, &Widget::resetIdleState, idleState);
    cameraState->addTransition(this, &Widget::resetIdleState, idleState);
    resetStartedState->addTransition(this, &Widget::resetIdleState, idleState);


    forScanState->addTransition(this, &Widget::resetForScanState, forScanState);
    cameraState->addTransition(this, &Widget::resetForScanState, forScanState);
    resetStartedState->addTransition(this, &Widget::resetForScanState, forScanState);

    // 配置状态转换
    QSignalTransition *idleState_To_ForScanState = idleState->addTransition(this, &Widget::toNextState, forScanState);
    connect(idleState_To_ForScanState, &QSignalTransition::triggered, this, &Widget::do_idleState_To_ForScanState);


    QSignalTransition *forScanState_To_CameraState = forScanState->addTransition(this, &Widget::toNextState, cameraState);
    connect(forScanState_To_CameraState, &QSignalTransition::triggered, this, &Widget::do_forScanState_To_CameraState);


    QSignalTransition *cameraState_To_ResetStartedState = cameraState->addTransition(this, &Widget::toNextState, resetStartedState);
    connect(cameraState_To_ResetStartedState, &QSignalTransition::triggered, this, &Widget::do_cameraState_To_ResetStartedState);


    QSignalTransition *resetStartedState_To_idleState = resetStartedState->addTransition(this, &Widget::toNextState, forScanState);
    connect(resetStartedState_To_idleState, &QSignalTransition::triggered, this, &Widget::do_resetStartedState_To_idleState);


    cameraSelfTest = new QState(idleState); // 相机自检
    lightSelfTest = new QState(idleState); // 光源自检
    cameraConnSelfTest = new QState(idleState); // 镜头自检

    plcSelfTest = new QState(idleState); // PLC自检
    industrialCtrlNetSelfTest = new QState(idleState); // 工控网自检
    secretMachineSelfTest = new QState(idleState); // 国密机自检


    finalSelfTest = new QFinalState(idleState);// 完成系统自检

    idleState->setInitialState(cameraSelfTest);// 设置相机自检为初始化状态
//    idleState->setInitialState(finalSelfTest);// 设置相机自检为初始化状态


    // 配置状态转换
    QSignalTransition *cameraSelfTest_To_lightSelfTest = cameraSelfTest->addTransition(this, &Widget::toNextState, lightSelfTest);
    connect(cameraSelfTest_To_lightSelfTest, &QSignalTransition::triggered, this, &Widget::do_cameraSelfTest_To_lightSelfTest);

    // 当 idleState 完成时，自动切换到 forScanState
//    idleState->addTransition(idleState, SIGNAL(finished()), forScanState);


    QSignalTransition *lightSelfTest_To_CameraState = lightSelfTest->addTransition(this, &Widget::toNextState, cameraConnSelfTest);
    connect(lightSelfTest_To_CameraState, &QSignalTransition::triggered, this, &Widget::do_lightSelfTest_To_CameraState);


    QSignalTransition *cameraConnSelfTest_To_plcSelfTest = cameraConnSelfTest->addTransition(this, &Widget::toNextState, plcSelfTest);
    connect(cameraConnSelfTest_To_plcSelfTest, &QSignalTransition::triggered, this, &Widget::do_cameraConnSelfTest_To_plcSelfTest);

//    resetStartedState->addTransition(resetStartedState, SIGNAL(finished()), idleState);

    QSignalTransition *plcSelfTest_To_industrialCtrlNetSelfTest = plcSelfTest->addTransition(this, &Widget::toNextState, industrialCtrlNetSelfTest);
    connect(plcSelfTest_To_industrialCtrlNetSelfTest, &QSignalTransition::triggered, this, &Widget::do_plcSelfTest_To_industrialCtrlNetSelfTest);


    QSignalTransition *industrialCtrlNetSelfTest_To_industrialCtrlNetSelfTest = industrialCtrlNetSelfTest->addTransition(this, &Widget::toNextState, secretMachineSelfTest);
    connect(industrialCtrlNetSelfTest_To_industrialCtrlNetSelfTest, &QSignalTransition::triggered, this, &Widget::do_industrialCtrlNetSelfTest_To_industrialCtrlNetSelfTest);


    QSignalTransition *secretMachineSelfTest_To_finalSelfTest = secretMachineSelfTest->addTransition(this, &Widget::toNextState, finalSelfTest);
    connect(secretMachineSelfTest_To_finalSelfTest, &QSignalTransition::triggered, this, &Widget::do_secretMachineSelfTest_To_finalSelfTest);

//        QState *scanSucceededState = new QState(forScanState);// 扫描成功

    waitingForScanState = new QState(forScanState);

    writBbufferState = new QState(forScanState); // 写缓冲区

    workpieceArrives1 = new QState(forScanState); // 工件到达工位一

    ForScanFinal = new QFinalState(forScanState);// 上料完成

    forScanState->setInitialState(waitingForScanState);// 设置等待扫描为初始化状态
//    forScanState->setInitialState(ForScanFinal);

    QSignalTransition *waitingForScanState_To_writBbufferState = waitingForScanState->addTransition(this, &Widget::toNextState, writBbufferState);
    connect(waitingForScanState_To_writBbufferState, &QSignalTransition::triggered, this, &Widget::do_waitingForScanState_To_writBbufferState);

    QSignalTransition *writBbufferState_To_workpieceArrives1 = writBbufferState->addTransition(this, &Widget::toNextState, workpieceArrives1);
    connect(writBbufferState_To_workpieceArrives1, &QSignalTransition::triggered, this, &Widget::do_writBbufferState_To_workpieceArrives1);

    QSignalTransition *workpieceArrives1_To_ForScanFinal = workpieceArrives1->addTransition(this, &Widget::toNextState, ForScanFinal);
    connect(workpieceArrives1_To_ForScanFinal, &QSignalTransition::triggered, this, &Widget::do_workpieceArrives1_To_ForScanFinal);


    photoTop = new QState(cameraState);   // 拍顶部
    photoFaceA = new QState(cameraState); // 拍A面
    photoFaceB = new QState(cameraState); // 拍B面
    photoFaceC = new QState(cameraState); // 拍C面
    photoFaceD = new QState(cameraState); // 拍D面
    photoBottom = new QState(cameraState);// 拍底面

    cameraFinal = new QFinalState(cameraState);

    cameraState->setInitialState(photoTop);// 设置顶部拍摄为初始化状态
//    cameraState->setInitialState(cameraFinal);

    QSignalTransition *photoTop_To_photoFaceA = photoTop->addTransition(this, &Widget::toNextState, photoFaceA);
    connect(photoTop_To_photoFaceA, &QSignalTransition::triggered, this, &Widget::do_photoTop_To_photoFaceA);

    QSignalTransition *photoFaceA_To_photoFaceB = photoFaceA->addTransition(this, &Widget::toNextState, photoFaceB);
    connect(photoFaceA_To_photoFaceB, &QSignalTransition::triggered, this, &Widget::do_photoFaceA_To_photoFaceB);

    QSignalTransition *photoFaceB_To_photoFaceC = photoFaceB->addTransition(this, &Widget::toNextState, photoFaceC);
    connect(photoFaceB_To_photoFaceC, &QSignalTransition::triggered, this, &Widget::do_photoFaceB_To_photoFaceC);


    QSignalTransition *photoFaceC_To_photoFaceD = photoFaceC->addTransition(this, &Widget::toNextState, photoFaceD);
    connect(photoFaceC_To_photoFaceD, &QSignalTransition::triggered, this, &Widget::do_photoFaceC_To_photoFaceD);


    QSignalTransition *photoFaceD_To_photoBottom = photoFaceD->addTransition(this, &Widget::toNextState, photoBottom);
    connect(photoFaceD_To_photoBottom, &QSignalTransition::triggered, this, &Widget::do_photoFaceD_To_photoBottom);


    QSignalTransition *photoBottom_To_cameraFinal = photoBottom->addTransition(this, &Widget::toNextState, cameraFinal);
    connect(photoBottom_To_cameraFinal, &QSignalTransition::triggered, this, &Widget::do_photoBottom_To_cameraFinal);

    cuttingSensorStatus = new QState(resetStartedState);// 产品下料
    SingleJobResetComplete = new QState(resetStartedState);// 单一工件复位
    resetStatus = new QState(resetStartedState);        // 复位状态

    resetFinal = new QFinalState(resetStartedState);// 下料完成

    resetStartedState->setInitialState(cuttingSensorStatus); // 设置产品下料为初始化状态
//    cameraState->setInitialState(resetFinal);

    QSignalTransition *cuttingSensorStatus_To_SingleJobResetComplete = cuttingSensorStatus->addTransition(this, &Widget::toNextState, SingleJobResetComplete);
    connect(cuttingSensorStatus_To_SingleJobResetComplete, &QSignalTransition::triggered, this, &Widget::do_cuttingSensorStatus_To_SingleJobResetComplete);

    QSignalTransition *SingleJobResetComplete_To_resetStatus = SingleJobResetComplete->addTransition(this, &Widget::toNextState, resetStatus);
    connect(SingleJobResetComplete_To_resetStatus, &QSignalTransition::triggered, this, &Widget::do_SingleJobResetComplete_To_resetStatus);

    QSignalTransition *resetStatus_To_resetFinal = resetStatus->addTransition(this, &Widget::toNextState, resetFinal);
    connect(resetStatus_To_resetFinal, &QSignalTransition::triggered, this, &Widget::do_resetStatus_To_resetFinal);

    // 连接定时器信号绑定槽函数
    initMachineConnectEnteredExited();
    initMachineConnectFinish();
    initIdleStateConnectEnteredExited();
    initForScanStateConnectEnteredExited();
    initCameraStateConnectEnteredExited();
    initResetStateConnectEnteredExited();
}

void Widget::do_idleState_To_ForScanState()
{
    qDebug() << "初始化完成，等待扫描...";
}

void Widget::do_forScanState_To_CameraState()
{
    qDebug() << "准备拍照...";
}

void Widget::do_cameraState_To_ResetStartedState()
{
    qDebug() << "所有拍照完成，准备下料...";
}

void Widget::do_resetStartedState_To_idleState()
{
    qDebug() << "下料完成，准备复位开始下次流程...";
}

void Widget::do_cameraSelfTest_To_lightSelfTest()
{
    qDebug() << "相机自检...";

//    ui->label_devCurrState->setStyleSheet("color:black");
//    ui->label_devCurrState->setText("正在拼命初始化，需要一些时间，请等待...");

//    ui->btn_switch->setEnabled(false);
//    ui->btn_codeScanStart->setEnabled(false);
//    m_nextStateFlag = true;// 状态机跳转开启
}

void Widget::do_lightSelfTest_To_CameraState()
{
    qDebug() << "光源自检...";
}

void Widget::do_lightSelfTest_To_cameraConnSelfTest()
{
    qDebug() << "镜头自检...";
}

void Widget::do_cameraConnSelfTest_To_plcSelfTest()
{
    qDebug() << "PLC自检...";
}

void Widget::do_plcSelfTest_To_industrialCtrlNetSelfTest()
{
    qDebug() << "工控网自检...";
}

void Widget::do_industrialCtrlNetSelfTest_To_industrialCtrlNetSelfTest()
{
    qDebug() << "国密机自检...";
}

void Widget::do_secretMachineSelfTest_To_finalSelfTest()
{
    qDebug() << "完成系统自检...";
}


void Widget::do_waitingForScanState_To_writBbufferState()
{
    qDebug() << "扫码成功，开始写缓冲区，开始上料，倍速链启动...";
}

void Widget::do_writBbufferState_To_workpieceArrives1()
{
    qDebug() << "工件到达工位一...";
}


void Widget::do_workpieceArrives1_To_ForScanFinal()
{
    qDebug() << "A位顶升，准备拍顶部...";
}

void Widget::do_photoTop_To_photoFaceA()
{
    qDebug() << "顶部拍摄完毕，准备拍A面...";
}

void Widget::do_photoFaceA_To_photoFaceB()
{
    qDebug() << "A面拍摄完毕，准备拍B面...";
}

void Widget::do_photoFaceB_To_photoFaceC()
{
    qDebug() << "B面拍摄完毕，准备拍C面...";
}

void Widget::do_photoFaceC_To_photoFaceD()
{
    qDebug() << "C面拍摄完毕，准备拍D面...";
}

void Widget::do_photoFaceD_To_photoBottom()
{
    qDebug() << "D面拍摄完毕，A位下降，移往工位二，准备拍底部...";
}


void Widget::do_photoBottom_To_cameraFinal()
{
    qDebug() << "底部拍摄完毕，准备下料...";
}



void Widget::do_cuttingSensorStatus_To_SingleJobResetComplete()
{
    qDebug() << "产品下料完毕，开始单一工位复位...";
}

void Widget::do_SingleJobResetComplete_To_resetStatus()
{
    qDebug() << "单一工位复位完毕，工件运输至出口...";
}

void Widget::do_resetStatus_To_resetFinal()
{
    qDebug() << "工件到达出口处，AGV接驳完毕，下料完毕...";
}


void Widget::onTimeoutStateMachine()
{
    static uint16_t time_count = 0;

    time_count++;

    if(false == m_getHttpCsvFlag)
    {
        // 周期性获取CSV
        uint16_t getCsvPostCount = time_count %= m_getHttpCsvTime_S;

        qDebug() << " m_getHttpCsvFlag: " << m_getHttpCsvFlag
                  << " getCsvPostCount: " << getCsvPostCount
                  << " time_count: " << time_count;

        if(0 == getCsvPostCount)
        {
            m_getHttpCsvFlag = true;
        }
    }

    // 周期性检查端口连接状态
    if(true == m_checkPortFlag)
    {
        uint16_t checkPortCount = time_count %= m_checkPortTime;
        if(0 == checkPortCount)
        {
            qDebug() << "检查各个端口连接状态...";

            // 更新端口连接状态
            updatePortConnectStatus();

        }
    } 


    if(m_nextStateFlag)
    {
        qDebug() << "--正在进行当前状态的任务---->";
        emit toStateWork();
//        m_nextStateFlag = false;
    }
}

void Widget::updatePortConnectStatus()
{
    // PLC端口，连接状态更新
    if(plc_port.checkConnectState())
    {
//        ui->LineEdit_PlcState->setText("已连接");
        setTextColor(ui->LineEdit_PlcState, "已连接", Qt::green);
    } else {
//        ui->LineEdit_PlcState->setText("已断开");
        setTextColor(ui->LineEdit_PlcState, "已断开", Qt::red);
    }

    // 工位1顶部光源端口，连接状态更新
    if(top_side_light_sport.checkConnectState())
    {
//        ui->LineEdit_lightConnStateA->setText("已连接");
//        ui->LineEdit_lightConnStateA_2->setText("已连接");
        setTextColor(ui->LineEdit_lightConnStateA, "已连接", Qt::green);
        setTextColor(ui->LineEdit_lightConnStateA_2, "已连接", Qt::green);
    } else {
//        ui->LineEdit_lightConnStateA->setText("已断开");
//        ui->LineEdit_lightConnStateA_2->setText("已断开");
        setTextColor(ui->LineEdit_lightConnStateA, "已断开", Qt::red);
        setTextColor(ui->LineEdit_lightConnStateA_2, "已断开", Qt::red);
    }

    // 工位1顶部镜头调焦端口,连接状态更新
    if(top_cam_focus_sport.checkConnectState())
    {
//        ui->LineEdit_cameraConnStateA->setText("已连接");
        setTextColor(ui->LineEdit_cameraConnStateA, "已连接", Qt::green);
    } else {
//        ui->LineEdit_cameraConnStateA->setText("已断开");
        setTextColor(ui->LineEdit_cameraConnStateA, "已断开", Qt::red);
    }

    // 工位2底部光源端口,连接状态更新
    if(bottom_light_sport.checkConnectState())
    {
//        ui->LineEdit_otherInfo_2->setText("已连接");
        setTextColor(ui->LineEdit_otherInfo_2, "已连接", Qt::green);
    } else {
//        ui->LineEdit_otherInfo_2->setText("已断开");
        setTextColor(ui->LineEdit_otherInfo_2, "已断开", Qt::red);
    }

    // 工位2底部光源端口,连接状态更新
    if(side_cam_focus_sport.checkConnectState())
    {
//        ui->LineEdit_cameraConnStateB->setText("已连接");
        setTextColor(ui->LineEdit_cameraConnStateB, "已连接", Qt::green);
    } else {
//        ui->LineEdit_cameraConnStateB->setText("已断开");
        setTextColor(ui->LineEdit_cameraConnStateB, "已断开", Qt::red);
    }
}

void Widget::do_Work_cameraSelfTest()
{
    qDebug() << "相机自检的操作...";
    bool flag = true;
    if(flag)
    {

//        if(device_switch_flag)
        {
            emit toNextState();
        }
    }
}


void Widget::do_Work_lightSelfTest()
{
    qDebug() << "光源自检的操作...";

    static uint8_t lightTestState = 1;

    QString toplight = "";

    if(lightTestState)
    {
        toplight = ensureThreeDigits(map_currentGroup.value("topCameraLightValue"));
        sendTopRoSideLightAdjustData(QString("SA0%1#SB0%2#").arg(toplight).arg(toplight));


        toplight = ensureThreeDigits(map_currentGroup.value("sideCameraLightValue"));
        sendTopRoSideLightAdjustData(QString("SC0%1#SD0%2#").arg(toplight).arg(toplight));


        toplight = ensureThreeDigits(map_currentGroup.value("sideCameraBottomLightValue"));
        sendBottomLightAdjustData(QString("SB0%1#").arg(toplight));


        toplight = ensureThreeDigits(map_currentGroup.value("bottomCameraLightValue"));
        sendBottomLightAdjustData(QString("SA0%1#").arg(toplight));

        lightTestState = !lightTestState;
    }
    else
    {
        lightTestState = !lightTestState;
        sendBottomLightAdjustData("SA0000#SB0000#");
        sendTopRoSideLightAdjustData("SA0000#SB0000#SC0000#SD0000#");

        emit toNextState();
    }
}

void Widget::do_Work_cameraConnSelfTest()
{
    qDebug() << "镜头自检的操作...";
    bool flag = true;
    uint8_t time = 5;
    static uint8_t count = 0;
    if(flag)
    {
        int16_t topCameraFoucs = map_currentGroup.value("topCameraFoucs").toInt();
        int16_t sideCameraFoucs = map_currentGroup.value("sideCameraFoucs").toInt();

        count++;

        qDebug() << "count:" << count << "time:" << time;
        if(0 == (count % time))
        {
            switch (count/time) {
            case 1:{
                sendTopFormSetData(1480);
            }break;
            case 2:{
                if(topCameraFoucs < 0){

                   topCameraFoucs = -topCameraFoucs + 740;
                } else {
                   topCameraFoucs = 740 - topCameraFoucs;
                }
                sendTopFormSetData(-topCameraFoucs);
                Dialog_camAdjust::topCamadjustValue = map_currentGroup.value("topCameraFoucs").toInt();
            }break;
            case 3:{
                sendSideFormSetData(1480);
            }break;
            case 4:{
                //                qDebug() << "sideCameraFoucs:" << sideCameraFoucs;
                if(sideCameraFoucs < 0){

                    sideCameraFoucs = -sideCameraFoucs + 740;
                } else {
                    sideCameraFoucs = 740 - sideCameraFoucs;
                }
                //                qDebug() << "sideCameraFoucs:" << -sideCameraFoucs;
                sendSideFormSetData(-sideCameraFoucs);
                Dialog_camAdjust::sideCamadjustValue = map_currentGroup.value("sideCameraFoucs").toInt();
            }break;
            default:
                count=0;
                emit toNextState();
                break;
            }
        }
    }
}

void Widget::do_Work_plcSelfTest()
{
    qDebug() << "plc自检的操作...";
    bool flag = true;
    if(flag)
    {
        if(m_portGlobalFlag == true)
        {
            emit toNextState();
        }
    }
}

void Widget::do_Work_industrialCtrlNetSelfTest()
{
    qDebug() << "工控网自检的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_secretMachineSelfTest()
{
    qDebug() << "国密机自检的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_finalSelfTest()
{
    qDebug() << "系统自检完成的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_waitingForScanState()
{
    ui->label_devCurrState->setStyleSheet("color:black");
    ui->label_devCurrState->setText("启动，开始获取任务...");

    qDebug() << "等待扫码枪扫码的操作...";
    bool flag = true;
    QMap<QString, QVariant> resultMap;
    QString productCode;

    qDebug() << "flag: " << flag << " m_getHttpCsvFlag: " << m_getHttpCsvFlag
             << " m_productCodeFlag: " << m_productCodeFlag
             << " m_productUniqueCode: " << m_productUniqueCode;

    if(true == m_getHttpCsvFlag)
    {
        if(false == m_productCodeFlag)
        {
            // 发送拍照请求，接收拍照完成数据
            // m_http->sendCsvJson(m_http, "/largeDeviceSystem/saveCsvFile", "csv/hello1.csv");

            // 获取CSV文件数据
            m_http->GetCsvUploadInfo("/largeDeviceSystem/getTaskCsvFile","");

            if(200 == HttpRequest::m_map_get.value("code").toInt())
            {
                ui->LineEdit_netWorkStatus->setText("已连接");

                qDebug() << "成功获取到CSV文件数据...";
                qDebug() << "file(未解码)" << HttpRequest::m_map_get.value("file").toString();
                qDebug() << "file(解码GBK)" << HttpRequest::m_map_get.value("file_GBK").toString();
                qDebug() << "file(解码UTF-8)" << HttpRequest::m_map_get.value("file_UTF8").toString();

                resultMap.clear();
                resultMap = parseCsvToMap(HttpRequest::m_map_get.value("file_UTF8").toString());

                productCode = HttpRequest::m_map_get.value("productUniqueCode").toString();
                // resultMap.value("产品码").toString();
                QString size = ui->LineEdit_workGroupSize->text();
                QString name = ui->LineEdit_currentWorkGroup->text();

                if(!productCode.isEmpty())
                {
                    Dialog_InputCode *dialog = new Dialog_InputCode(nullptr, productCode, name, size);

                    if(dialog->exec() == QDialog::Accepted)
                    {
                        do_checkCode(productCode);
                        m_productCodeFlag = true;
                        m_productUniqueCode = productCode;
                    } else {
                        m_productUniqueCode.clear();
                        m_getHttpCsvFlag = true;
                        m_productCodeFlag = false;
                        // emit resetIdleState();
                        emit resetForScanState();// 跳转到等待扫描
                    }
                    delete dialog;
                }
            }
        }
        m_getHttpCsvFlag = false;
    }


    qDebug() << "当前状态码：" << plcStateBit;
    if(plcStateBit >= 3 && m_productCodeFlag == true)
    {
        qDebug() << "resultMap:" << resultMap;
        if(!resultMap.isEmpty())
        {
            // 打印结果
            for (auto it = resultMap.constBegin(); it != resultMap.constEnd(); ++it) {
                qDebug() << it.key() << ":" << it.value().toString();
            }
        }

        m_productUniqueCode.clear();
        m_getHttpCsvFlag = true;
        m_productCodeFlag = false;
        emit toNextState();
    }

}

void Widget::do_Work_writBbufferState()
{
    qDebug() << "写缓冲区的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_workpieceArrives1()
{
    qDebug() << "工件到达工位一的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_ForScanFinal()
{
    qDebug() << "上料完成的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}


bool Widget::sendPhotoFinishPost(QMap<QString, QString> postData)
{
    bool flag = false;
    // 发送拍照请求，接收拍照完成数据
//        m_http->sendCsvJson(m_http, "/largeDeviceSystem/saveCsvFile", "csv/hello1.csv");
    m_http->NormalPostRequest("/largeDeviceSystem/saveCsvFile", postData);

    qDebug() << "code:" << HttpRequest::m_map_post.value("code").toInt();
    if(200 == HttpRequest::m_map_post.value("code").toInt())
    {
        qDebug() << "file(未解码)" << HttpRequest::m_map_post.value("file").toString();
        qDebug() << "file(解码GBK)" << HttpRequest::m_map_post.value("file_GBK").toString();
        qDebug() << "file(解码UTF-8)" << HttpRequest::m_map_post.value("file_UTF8").toString();

        flag = true;
    }

    return flag;
}

QMap<QString, QString> Widget::getCsvPhotoJson(const QString &productUniqueCode, const QString &cameraCode, const QString &cameraStatus, const QString &takePhotoNum)
{
    QJsonObject obj;

    obj.insert("productUniqueCode", productUniqueCode);
    obj.insert("cameraCode", cameraCode);
    obj.insert("cameraStatus", "0");
    obj.insert("exposureTime", 8000);
    obj.insert("takePhotoNum", takePhotoNum);
    QJsonDocument csvJsonDoc(obj);

    // 将 QJsonDocument 转换为格式化的 JSON 字符串
    QString jsonString = csvJsonDoc.toJson(QJsonDocument::Indented);

    QMap<QString, QString> map_post;
    map_post.insert("file", jsonString);

    return map_post;
}

void Widget::do_Work_photoTop()
{
    qDebug() << "拍顶部的操作...";
    static bool flag = true;
    static uint8_t timeCount = 0;


    if(m_topPhotoFinishFlag == false)
    {
        if(0x01 == m_topPhotoRequest)
            m_topPhotoFinishFlag = sendPhotoFinishPost(getCsvPhotoJson("1232","1", "0","1"));
    } else {
        if(0x02 != m_topPhotoRequest || true == flag)
        {
            flag = false;
            qDebug() << "发送-->顶部拍照 finish";
            plc_port.sendModbusRequest(0x06, 0x00, 0x02);
        }
        timeCount++;
        qDebug() << "timeCount+1...";
    }

    qDebug() << "timeCount" << timeCount
             << "timeCount >= m_timeCountFinishVal" << (timeCount >= m_timeCountFinishVal)
             << "m_topPhotoFinishFlag" << m_topPhotoFinishFlag;

    // 延时m_timeCountFinishVal秒后，进入
    if(timeCount >= m_timeCountFinishVal)
    {
        flag = true;
        timeCount = 0;

        qDebug() << "当前状态码：" << plcStateBit;
        qDebug() << "PLC_TOP:" << m_topPhotoRequest
                 << "HTTP_TOP:" << m_topPhotoFinishFlag;
        if((plcStateBit > 6 && 0x02 == m_topPhotoRequest ) && m_topPhotoFinishFlag)
        {
            m_topPhotoFinishFlag = false;
            QMap<QString, QVariant> resultMap = parseCsvToMap(HttpRequest::m_map_get.value("file_UTF8").toString());
//            qDebug() << "resultMap:" << resultMap;
//            if(!resultMap.isEmpty())
//            {
//                // 打印结果
//                for (auto it = resultMap.constBegin(); it != resultMap.constEnd(); ++it) {
//                    qDebug() << it.key() << ":" << it.value().toString();
//                }
//            }
            emit toNextState();
        }
    }

}

void Widget::do_Work_photoFaceA()
{
    qDebug() << "拍A面的操作...";
    static bool flag = true;
    static uint8_t timeCount = 0;

    if(false == m_AsidePhotoFinishFlag)
    {
        if(0x01 == m_ABCD_PhotoRequest)
            m_AsidePhotoFinishFlag = sendPhotoFinishPost(getCsvPhotoJson("1232","2", "0","1"));
    } else {
        if(m_ABCD_PhotoRequest != 0x02 || true == flag)
        {
            flag = false;
            qDebug() << "发送-->A面拍照 finish";
            plc_port.sendModbusRequest(0x06, 0x01, 0x02);
        }
        timeCount++;
        qDebug() << "timeCount+1...";
    }

    qDebug() << "timeCount" << timeCount
              << "timeCount >= m_timeCountFinishVal" << (timeCount >= m_timeCountFinishVal)
              << "m_AsidePhotoFinishFlag" << m_AsidePhotoFinishFlag;

    if(timeCount >= m_timeCountFinishVal)
    {
        flag = true;
        timeCount = 0;

        qDebug() << "当前状态码：" << plcStateBit;
        qDebug() << "PLC_ABCD:" << m_ABCD_PhotoRequest
                  << "HTTP_A:" << m_AsidePhotoFinishFlag;
        if((plcStateBit > 10 && 0x02 == m_ABCD_PhotoRequest )&& m_AsidePhotoFinishFlag)
        {
            m_AsidePhotoFinishFlag = false;
            QMap<QString, QVariant> resultMap = parseCsvToMap(HttpRequest::m_map_post.value("file_GBK").toString());
//            qDebug() << "resultMap:" << resultMap;
//            if(!resultMap.isEmpty())
//            {
//                // 打印结果
//                for (auto it = resultMap.constBegin(); it != resultMap.constEnd(); ++it) {
//                    qDebug() << it.key() << ":" << it.value().toString();
//                }
//            }
            emit toNextState();
        }   
    }
}

void Widget::do_Work_photoFaceB()
{
    qDebug() << "拍B面的操作...";
    static bool flag = true;
    static uint8_t timeCount = 0;

    if(false == m_BsidePhotoFinishFlag)
    {
        if(0x01 == m_ABCD_PhotoRequest)
            m_BsidePhotoFinishFlag = sendPhotoFinishPost(getCsvPhotoJson("1232","2", "0","1"));
    } else {
        if(m_ABCD_PhotoRequest != 0x02 || true == flag)
        {
            flag = false;
            qDebug() << "发送-->B面拍照 finish";
            plc_port.sendModbusRequest(0x06, 0x01, 0x02);
        }
        timeCount++;
        qDebug() << "timeCount+1...";
    }

    qDebug() << "timeCount" << timeCount
              << "timeCount >= m_timeCountFinishVal" << (timeCount >= m_timeCountFinishVal)
              << "m_BsidePhotoFinishFlag" << m_BsidePhotoFinishFlag;

    if(timeCount >= m_timeCountFinishVal)
    {
        flag = true;
        timeCount = 0;

        qDebug() << "当前状态码：" << plcStateBit;
        qDebug() << "PLC_ABCD:" << m_ABCD_PhotoRequest
                  << "HTTP_B:" << m_BsidePhotoFinishFlag;
        if((plcStateBit > 13 && 0x02 == m_ABCD_PhotoRequest ) && m_BsidePhotoFinishFlag)
        {
            m_BsidePhotoFinishFlag = false;
            QMap<QString, QVariant> resultMap = parseCsvToMap(HttpRequest::m_map_post.value("file_GBK").toString());
//            qDebug() << "resultMap:" << resultMap;
//            if(!resultMap.isEmpty())
//            {
//                // 打印结果
//                for (auto it = resultMap.constBegin(); it != resultMap.constEnd(); ++it) {
//                    qDebug() << it.key() << ":" << it.value().toString();
//                }
//            }
            emit toNextState();
        }
    }
}

void Widget::do_Work_photoFaceC()
{
    qDebug() << "拍C面的操作...";
    static bool flag = true;
    static uint8_t timeCount = 0;

    if(false == m_CsidePhotoFinishFlag)
    {
        if(0x01 == m_ABCD_PhotoRequest)
            m_CsidePhotoFinishFlag = sendPhotoFinishPost(getCsvPhotoJson("1232","2", "0","1"));
    } else {
        if(m_ABCD_PhotoRequest != 0x02 || true == flag)
        {
            flag = false;
            qDebug() << "发送-->C面拍照 finish";
            plc_port.sendModbusRequest(0x06, 0x01, 0x02);
        }
        timeCount++;
        qDebug() << "timeCount+1...";
    }


    qDebug() << "timeCount" << timeCount
              << "timeCount >= m_timeCountFinishVal" << (timeCount >= m_timeCountFinishVal)
              << "m_CsidePhotoFinishFlag" << m_CsidePhotoFinishFlag;

    if(timeCount >= m_timeCountFinishVal)
    {
        flag = true;
       timeCount = 0;

        qDebug() << "当前状态码：" << plcStateBit;
        qDebug() << "PLC_ABCD:" << m_ABCD_PhotoRequest
                  << "HTTP_C:" << m_CsidePhotoFinishFlag;
        if(( plcStateBit > 16 && 0x02 == m_ABCD_PhotoRequest ) && m_CsidePhotoFinishFlag)
        {
            m_CsidePhotoFinishFlag = false;
            QMap<QString, QVariant> resultMap = parseCsvToMap(HttpRequest::m_map_post.value("file_GBK").toString());
//            qDebug() << "resultMap:" << resultMap;
//            if(!resultMap.isEmpty())
//            {
//                // 打印结果
//                for (auto it = resultMap.constBegin(); it != resultMap.constEnd(); ++it) {
//                    qDebug() << it.key() << ":" << it.value().toString();
//                }
//            }
            emit toNextState();
        }
    }
}

void Widget::do_Work_photoFaceD()
{
    qDebug() << "拍D面的操作...";
    static bool flag = true;
    static uint8_t timeCount = 0;

    if(false == m_DsidePhotoFinishFlag)
    {
        if(0x01 == m_ABCD_PhotoRequest)
            m_DsidePhotoFinishFlag = sendPhotoFinishPost(getCsvPhotoJson("1232","2", "0","1"));
    } else {
        if(m_ABCD_PhotoRequest != 0x02 || true == flag)
        {
            flag = false;
            qDebug() << "发送-->D面拍照 finish";
            plc_port.sendModbusRequest(0x06, 0x01, 0x02);
        }
        timeCount++;
        qDebug() << "timeCount+1...";
    }

    qDebug() << "timeCount" << timeCount
              << "timeCount >= m_timeCountFinishVal" << (timeCount >= m_timeCountFinishVal)
              << "m_DsidePhotoFinishFlag" << m_DsidePhotoFinishFlag;

    if(timeCount >= m_timeCountFinishVal)
    {
        flag = true;
       timeCount = 0;

        qDebug() << "当前状态码：" << plcStateBit;
        qDebug() << "PLC_ABCD:" << m_ABCD_PhotoRequest
                  << "HTTP_D:" << m_DsidePhotoFinishFlag;
        if((plcStateBit > 19 && 0x02 == m_ABCD_PhotoRequest ) && m_DsidePhotoFinishFlag)
        {
            m_DsidePhotoFinishFlag = false;
            QMap<QString, QVariant> resultMap = parseCsvToMap(HttpRequest::m_map_post.value("file_GBK").toString());
//            qDebug() << "resultMap:" << resultMap;
//            if(!resultMap.isEmpty())
//            {
//                // 打印结果
//                for (auto it = resultMap.constBegin(); it != resultMap.constEnd(); ++it) {
//                    qDebug() << it.key() << ":" << it.value().toString();
//                }
//            }
            emit toNextState();
        }
    }
}

void Widget::do_Work_photoBottom()
{
    qDebug() << "拍底部的操作...";
    static bool flag = true;
    static uint8_t timeCount = 0;


    if(false == m_bottomPhotoFinishFlag)
    {
        if( 0x01 == m_bottomPhotoRequest)
            m_bottomPhotoFinishFlag = sendPhotoFinishPost(getCsvPhotoJson("1232","3", "1","1"));
    } else {

        if(m_bottomPhotoRequest != 0x02 || true == flag)
        {
            flag = false;
            qDebug() << "发送-->底部拍照 finish";
            plc_port.sendModbusRequest(0x06, 0x02, 0x02);
        }
        timeCount++;
        qDebug() << "timeCount+1...";
    }

    qDebug() << "timeCount" << timeCount
              << "timeCount >= m_timeCountFinishVal" << (timeCount >= m_timeCountFinishVal)
              << "m_bottomPhotoFinishFlag" << m_bottomPhotoFinishFlag;

    // 延时
    if(timeCount >= m_timeCountFinishVal)
    {
        flag = true;
        timeCount = 0;

        qDebug() << "当前状态码：" << plcStateBit;
        qDebug() << "PLC_BOTTOM:" << m_bottomPhotoRequest
                  << "HTTP_BOTTOM:" << m_bottomPhotoFinishFlag;
        if(plcStateBit > 25 && 0x02 == m_bottomPhotoRequest && m_bottomPhotoFinishFlag)
        {
            m_bottomPhotoFinishFlag = false;
            emit toNextState();
        }
    }

}

void Widget::do_Work_cameraFinal()
{
    qDebug() << "所有拍照完成的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_cuttingSensorStatus()
{
    qDebug() << "产品下料的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_SingleJobResetComplete()
{
    qDebug() << "单一工件复位的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_resetStatus()
{
    qDebug() << "复位状态的操作...";
    bool flag = true;
    if(flag)
    {
        emit toNextState();
    }
}

void Widget::do_Work_resetFinal()
{
    qDebug() << "下料完成的操作...";
    bool flag = true;
    if(flag)
    {
        int plcState = ui->LineEdit_latestStatusCode->text().toInt();
        if(plcState <= 27)
        {
            emit toNextState();
        }

    }
}


void Widget::initMachineConnectEnteredExited()
{
    connect(idleState,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "idleState entered..";


        ui->label_devCurrState->setStyleSheet("color:black");
        ui->label_devCurrState->setText("正常");

    });
    connect(idleState,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "idleState exited..";
    });


    connect(forScanState,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "forScanState entered..";
    });
    connect(forScanState,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "forScanState exited..";
    });


    connect(cameraState,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "cameraState entered..";
    });
    connect(cameraState,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "cameraState exited..";
    });


    connect(resetStartedState,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "resetStartedState entered..";
    });
    connect(resetStartedState,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "resetStartedState exited..";
    });



    connect(stoppedState,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "stoppedState entered..";
    });
    connect(stoppedState,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "stoppedState exited..";
    });
}

// 初始化状态机，完成信号连接槽
void Widget::initMachineConnectFinish()
{
    connect(idleState,&QState::finished,this,[=](){
        qDebug() << __FUNCTION__ << "idleState finished..";
    });


    connect(forScanState,&QState::finished,this,[=](){
        qDebug() << __FUNCTION__ << "forScanState finished..";
    });


    connect(cameraState,&QState::finished,this,[=](){
        qDebug() << __FUNCTION__ << "cameraState finished..";
    });


    connect(resetStartedState,&QState::finished,this,[=](){
        qDebug() << __FUNCTION__ << "resetStartedState finished..";
    });


    connect(stoppedState,&QState::finished,this,[=](){
        qDebug() << __FUNCTION__ << "stoppedState finished..";
    });
}

void Widget::initIdleStateConnectEnteredExited()
{
    connect(cameraSelfTest,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "cameraSelfTest entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_cameraSelfTest);


        ui->label_devCurrState->setStyleSheet("color:black");
        ui->label_devCurrState->setText("正在初始化，请等待...");

        m_nextStateFlag = true;// 状态机跳转开启
        ui->btn_switch->setEnabled(false);
        ui->btn_codeScanStart->setEnabled(false);

    });
    connect(cameraSelfTest,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "cameraSelfTest exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_cameraSelfTest);
    });



    connect(lightSelfTest,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "lightSelfTest entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_lightSelfTest);
    });
    connect(lightSelfTest,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "lightSelfTest exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_lightSelfTest);
    });



    connect(cameraConnSelfTest,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "cameraConnSelfTest entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_cameraConnSelfTest);


    });
    connect(cameraConnSelfTest,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "cameraConnSelfTest exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_cameraConnSelfTest);
    });



    connect(plcSelfTest,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "plcSelfTest entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_plcSelfTest);
    });
    connect(plcSelfTest,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "plcSelfTest exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_plcSelfTest);
    });



    connect(industrialCtrlNetSelfTest,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "industrialCtrlNetSelfTest entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_industrialCtrlNetSelfTest);
    });
    connect(industrialCtrlNetSelfTest,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "industrialCtrlNetSelfTest exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_industrialCtrlNetSelfTest);
    });



    connect(secretMachineSelfTest,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "secretMachineSelfTest entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_secretMachineSelfTest);
    });
    connect(secretMachineSelfTest,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "secretMachineSelfTest exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_secretMachineSelfTest);
    });



    connect(finalSelfTest,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "finalSelfTest entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_finalSelfTest);

//        m_nextStateFlag = false;// 状态机跳转停止
//        ui->btn_switch->setEnabled(true);
//        ui->btn_codeScanStart->setEnabled(true);


//        ui->label_devCurrState->setStyleSheet("color:green");
//        ui->label_devCurrState->setText("初始化完成，等待启动^_^");
    });
    connect(finalSelfTest,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "finalSelfTest exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_finalSelfTest);

        //        ui->label_devCurrState->setStyleSheet("color:green");
        //        ui->label_devCurrState->setText("初始化完成");

    });
}

void Widget::initForScanStateConnectEnteredExited()
{
    connect(waitingForScanState,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "waitingForScanState entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_waitingForScanState);

        sendBottomLightAdjustData("SA0000#SB0000#");
        sendTopRoSideLightAdjustData("SA0000#SB0000#SC0000#SD0000#");

        m_productUniqueCode.clear();
        m_getHttpCsvFlag = true;
        m_productCodeFlag = false;


        m_nextStateFlag = false;// 状态机跳转停止
        ui->btn_switch->setEnabled(true);
        ui->btn_codeScanStart->setEnabled(true);


        ui->label_devCurrState->setStyleSheet("color:green");
        ui->label_devCurrState->setText("初始化完成");


        if(device_switch_flag == true)
        {
//              StateMachineTimer->stop();
            ui->btn_switch->click();
        }


//        ui->label_devCurrState->setStyleSheet("color:green");
//        ui->label_devCurrState->setText("等待启动");
//        ui->label_devCurrState->setStyleSheet("color:black");
//        ui->label_devCurrState->setText("启动...");
    });
    connect(waitingForScanState,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "waitingForScanState exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_waitingForScanState);

        ui->label_devCurrState->setStyleSheet("color:black");
        ui->label_devCurrState->setText("获取到任务，现在进行拍照...");
    });



    connect(writBbufferState,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "writBbufferState entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_writBbufferState);
    });
    connect(writBbufferState,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "writBbufferState exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_writBbufferState);
    });



    connect(workpieceArrives1,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "workpieceArrives1 entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_workpieceArrives1);
    });
    connect(workpieceArrives1,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "workpieceArrives1 exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_workpieceArrives1);
    });



    connect(ForScanFinal,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "ForScanFinal entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_ForScanFinal);
    });
    connect(ForScanFinal,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "ForScanFinal exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_ForScanFinal);
    });
}

void Widget::initCameraStateConnectEnteredExited()
{
    connect(photoTop,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "photoTop entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_photoTop);

        uint8_t topLight = map_currentGroup.value("topCameraLightValue").toUInt();

        QString channelA = Dialog_LightControl::getSetLightsDataString("A", topLight);
        QString channelB = Dialog_LightControl::getSetLightsDataString("B", topLight);

        QString sData = channelA + channelB;

        sendTopRoSideLightAdjustData("SC0000#SD0000#");
        sendBottomLightAdjustData("SB0000#");
        sendTopRoSideLightAdjustData(sData);
        sendTopRoSideLightAdjustData("SH#");// 顶部侧面 开灯
    });

    connect(photoTop,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "photoTop exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_photoTop);
    });

    connect(photoFaceA,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceA entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceA);

        uint8_t sideLight = map_currentGroup.value("sideCameraLightValue").toUInt();
        uint8_t sideBottomLight = map_currentGroup.value("sideCameraBottomLightValue").toUInt();

        QString channelC = Dialog_LightControl::getSetLightsDataString("C", sideLight);
        QString channelD = Dialog_LightControl::getSetLightsDataString("D", sideLight);

        QString channelB = Dialog_LightControl::getSetLightsDataString("B", sideBottomLight);

        QString sData = channelC + channelD;

        sendTopRoSideLightAdjustData("SA0000#SB0000#");
        sendBottomLightAdjustData(channelB);
        sendTopRoSideLightAdjustData(sData);
        sendTopRoSideLightAdjustData("SH#");// 顶部侧面 开灯

    });
    connect(photoFaceA,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceA exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceA);
    });



    connect(photoFaceB,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceB entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceB);
    });
    connect(photoFaceB,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceB exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceB);
    });



    connect(photoFaceC,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceC entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceC);
    });
    connect(photoFaceC,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceC exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceC);
    });

    connect(photoFaceD,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceD entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceD);
    });
    connect(photoFaceD,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "photoFaceD exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_photoFaceD);

        sendTopRoSideLightAdjustData("SA0000#SB0000#SC0000#SD0000#");// 关闭侧面所有光源

        uint8_t bottomCameraLightValue = map_currentGroup.value("bottomCameraLightValue").toUInt();

        QString channelA = Dialog_LightControl::getSetLightsDataString("A", bottomCameraLightValue);

        QString channelB = "SB0000#";

        QString sData = channelA + channelB;

        sendBottomLightAdjustData(sData);// 关闭侧面补光，打开底部相机光源

        sendBottomLightAdjustData("SH#");// 底部 开灯
    });

    connect(photoBottom,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "photoBottom entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_photoBottom);
    });
    connect(photoBottom,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "photoBottom exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_photoBottom);
    });


    connect(cameraFinal,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "cameraFinal entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_cameraFinal);

//        sendBottomLightAdjustData("SA0000#SB0000#");
        sendBottomLightAdjustData("SA0000#");
//        sendBottomLightAdjustData("SL#");
    });
    connect(cameraFinal,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "cameraFinal exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_cameraFinal);

    });
}

void Widget::initResetStateConnectEnteredExited()
{
    connect(cuttingSensorStatus,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "cuttingSensorStatus entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_cuttingSensorStatus);
    });
    connect(cuttingSensorStatus,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "cuttingSensorStatus exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_cuttingSensorStatus);
    });



    connect(SingleJobResetComplete,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "SingleJobResetComplete entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_SingleJobResetComplete);
    });
    connect(SingleJobResetComplete,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "SingleJobResetComplete exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_SingleJobResetComplete);
    });



    connect(resetStatus,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "resetStatus entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_resetStatus);
    });
    connect(resetStatus,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "resetStatus exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_resetStatus);
    });


    connect(resetFinal,&QState::entered,this,[=](){
        qDebug() << __FUNCTION__ << "resetFinal entered..";
        connect(this, &Widget::toStateWork, this, &Widget::do_Work_resetFinal);
    });
    connect(resetFinal,&QState::exited,this,[=](){
        qDebug() << __FUNCTION__ << "resetFinal exited..";
        disconnect(this, &Widget::toStateWork, this, &Widget::do_Work_resetFinal);


//        if(device_switch_flag == true)
//        {
////            StateMachineTimer->stop();
//            ui->btn_switch->click();
//        }

        ui->label_devCurrState->setStyleSheet("color:green");
        ui->label_devCurrState->setText("运行结束");
    });
}

void Widget::initIdleState()
{
    idleState->addTransition(this, &Widget::toNextState, ForScanFinal);

    forScanState->addTransition(this, &Widget::toNextState, cameraState);

    cameraState->addTransition(this, &Widget::toNextState, resetStartedState);

    resetStartedState->addTransition(this, &Widget::toNextState, idleState);
}


QMap<QString, QVariant> Widget::parseCsvToMap(const QString &csvString) {
    QMap<QString, QVariant> resultMap;

    // 按行分割 CSV 字符串
    QStringList lines = csvString.split("\n", QString::SkipEmptyParts);

    if (lines.size() < 2) {
        qWarning() << "CSV string does not contain enough lines.";
        return resultMap;
    }

    // 获取标题行和数据行
    QStringList headers = lines[0].split(",");
    QStringList values = lines[1].split(",");

    // 将标题和对应的值存入 QMap
    for (int i = 0; i < headers.size() && i < values.size(); ++i) {
        resultMap.insert(headers[i], values[i]);
    }

    return resultMap;
}


QString Widget::ensureThreeDigits(const QString &input) {
    QString strTemp = input;

    // 使用正则表达式匹配数字
    QRegExp numberRx("\\d+");
    if (numberRx.indexIn(strTemp) != -1) {
        QString numberStr = numberRx.cap(0); // 提取匹配到的数字
        int number = numberStr.toInt(); // 将字符串转换为整数
        // 使用QString的arg函数来格式化数字，确保至少三位，不足则补零
        return QString("%1").arg(number, 3, 10, QChar('0'));
    }
    // 如果输入字符串中没有数字，返回原始字符串或空字符串，根据你的需求
    if(strTemp.size() < 3) {
        strTemp.prepend('0');
    }
    return strTemp; // 或者 return QString();
}

void Widget::getScanStartProductCode(const QString &productCode)
{
    m_productCode = productCode;
}

void Widget::setTextColor(QLineEdit *le,const QString &text, const QColor &color)
{
    if (le == nullptr) {
        return;
    }

    le->setText(text);
    QPalette palette = le->palette();
    palette.setColor(QPalette::Text, color);
    le->setPalette(palette);
}


void Widget::on_btn_codeScanStart_clicked()
{
    // 使用封装后的类和函数
    if (MessageBoxUtil::Cancel == MessageBoxUtil::showMessage(this, MessageBoxUtil::Question, "检查产品尺寸",
        QString("请确认该产品的尺寸为: %1\n").arg(ui->LineEdit_workGroupSize->text()), MessageBoxUtil::Ok|MessageBoxUtil::Cancel)) {
        setTextColor(ui->LineEdit_systemVersion, "V1.0", Qt::red);
        return;
    } else {
        setTextColor(ui->LineEdit_systemVersion, "V1.0", Qt::green);
    }



//    Dialog_codeScanStart dialog;

//    connect(&dialog, &Dialog_codeScanStart::snedProductCode, this, &Widget::getScanStartProductCode);

//    if(dialog.exec() == QDialog::Accepted)
//    {
//        if(!m_productCode.isEmpty())
//        {
//            QString size = ui->LineEdit_workGroupSize->text();
//            QString name = ui->LineEdit_currentWorkGroup->text();

//            Dialog_InputCode *dialog = new Dialog_InputCode(nullptr, m_productCode, name, size);

//            if(dialog->exec() == QDialog::Accepted)
//            {
//                qDebug() << "------------------------->  扫码枪启动  <-------------------------";

//                do_checkCode(m_productCode);
////                m_productCodeFlag = true;
////                m_productUniqueCode = m_productCode;
////                ui->btn_switch->click();
//                emit toNextState(); // 跳转到下一个状态（跳过获取CSV任务状态）
//                m_nextStateFlag = true;// 状态机跳转开启
//            }
////            else {
////                m_productCode.clear();
//////                m_productUniqueCode.clear();
//////                m_getHttpCsvFlag = true;
//////                m_productCodeFlag = false;
//////                // emit resetIdleState();
//////                emit resetForScanState();// 跳转到等待扫描
////            }
//            m_productCode.clear();
//            delete dialog;
//        }
//    }
//    disconnect(&dialog, &Dialog_codeScanStart::snedProductCode, this, &Widget::getScanStartProductCode);
}



void Widget::deleteStateMachine()
{
    // 首先，停止状态机（如果它在运行）
    if (machine && machine->isRunning()) {
        machine->stop();
    }

    // 删除状态机及其所有状态
    delete finalSelfTest;
    delete plcSelfTest;
    delete industrialCtrlNetSelfTest;
    delete secretMachineSelfTest;
    delete cameraConnSelfTest;
    delete lightSelfTest;
    delete cameraSelfTest;
    delete stoppedState;
    delete resetStartedState;
    delete cameraState;
    delete forScanState;
    // delete stateInit;
    delete idleState;
    delete waitingForScanState;
    delete writBbufferState;
    delete workpieceArrives1;
    delete ForScanFinal;
    delete photoTop;
    delete photoFaceA;
    delete photoFaceB;
    delete photoFaceC;
    delete photoFaceD;
    delete photoBottom;
    delete cameraFinal;
    delete cuttingSensorStatus;
    delete SingleJobResetComplete;
    delete resetStatus;
    delete resetFinal;

    // 最后，删除状态机本身
    delete machine;

    // 将所有指针设置为nullptr，以防止悬空指针
    machine = nullptr;
    idleState = nullptr;
    // ... （对所有其他指针也做同样的操作）
}
